#include "keyboard.h"
#include "driver/i2c_master.h"
// #include "I2C.h"
#define DATA_LENGTH 2
i2c_master_dev_handle_t dev_handle;
i2c_master_bus_handle_t bus_handle;
uint16_t I2C_SimpleReadFromDevice(void)
{
    uint8_t buffer[2] = {0};
    i2c_master_receive(dev_handle, buffer, DATA_LENGTH, -1);
    // I2C_Read((0x65<<1)|1, buffer);
    return ((((uint16_t)buffer[0]) << 8) | buffer[1]);
}

uint8_t KEYBOARD_ReadKey(void)
{
    uint16_t content = I2C_SimpleReadFromDevice();
    // printf("content: %x\n", content);
    if (content == 0x0000) return 0xFF;
    if (content == 0x0100) return '1';
    if (content == 0x1000) return '2';
    if (content == 0x0001) return '3';
    if (content == 0x0200) return '4';
    if (content == 0x2000) return '5';
    if (content == 0x0002) return '6';
    if (content == 0x0400) return '7';
    if (content == 0x4000) return '8';
    if (content == 0x0004) return '9';
    if (content == 0x0800) return '*';
    if (content == 0x8000) return '0';
    if (content == 0x0008) return '#';
    if (content == 0x0010) return 'A';

    if (content == 0x0020) return 'B';
    if (content == 0x0040) return 'C';
    if (content == 0x0080) return 'D';
    return 0xFF;
}

/// GPIO初始化
void KEYBOARD_Init(void)
{
    // I2C_Init();
    i2c_master_bus_config_t i2c_mst_config = {
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .i2c_port = I2C_NUM_0,
        .scl_io_num = GPIO_NUM_1,
        .sda_io_num = GPIO_NUM_2,
        .glitch_ignore_cnt = 7,
    };


    ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));

    i2c_device_config_t dev_cfg = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = 0x65,
        .scl_speed_hz = 100000,
    };


    ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
    // 中断
    // POSEDGE：上升沿，positive edge
    // NEGEDGE：下降沿，negative edge
    gpio_config_t io_conf;
    io_conf.intr_type = GPIO_INTR_NEGEDGE;
    io_conf.mode = GPIO_MODE_INPUT;
    io_conf.pin_bit_mask = (1ULL << KEYBOARD_INT);
    gpio_config(&io_conf);
}


